from django.shortcuts import render
from django.http import HttpResponse
from data_api.models import *
from data_api.serializers import HotelRedGroundSerializer, HotelIdBindSerializer, HotelWhitePriceSerializer, \
    HotelItemXxSerializer, HotelXcIdSerializer
# Create your views here.
from rest_framework.decorators import api_view
from rest_framework import status
from rest_framework.response import Response
import json


# 城市热门酒店全部返回
@api_view(['GET', 'POST'])
def get_all(request, format=None):
    if request.method == 'GET':
        hotel_red_ground = HotelRedGround.objects.all()
        serializer = HotelRedGroundSerializer(hotel_red_ground, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = HotelRedGroundSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['GET'])
def get_list(request, format=None):
    if request.method == 'GET':
        hotel_red_ground = HotelRedGround.objects.values('hotel_id', 'name', 'path', 'city_code', 'other').distinct()
        obj = StandardResultSetPagination()
        page_list = obj.paginate_queryset(hotel_red_ground, request)
        ser = HotelRedGroundSerializer(instance=page_list, many=True)  # 多个many=True # instance：把对象序列化
        response = obj.get_paginated_response(ser.data)
        return response


@api_view(['GET', 'POST'])
def get_city_code(request, format=None):
    if request.method == 'GET':
        city_code = request.GET['city_code']
        if city_code is not None:
            hotel_red_ground = HotelRedGround.objects.filter(city_code=city_code)
            obj = StandardResultSetPagination()
            page_list = obj.paginate_queryset(hotel_red_ground, request)
            ser = HotelRedGroundSerializer(instance=page_list, many=True)
            response = obj.get_paginated_response(ser.data)
            return response
        else:
            return Response(str('请传city_code'))


@api_view(['GET'])
def get_bind(request, format=None):
    if request.method == 'GET':
        hotel_id_bind = HotelIdBind.objects.all()
        # http: // 127.0.0.1:8000 / get_bind?limit = 20 & offset = 40
        # 根据url参数 获取分页数据
        obj = StandardResultSetPagination()
        page_list = obj.paginate_queryset(hotel_id_bind, request)
        # 对数据序列化 普通序列化 显示的只是数据
        ser = HotelIdBindSerializer(instance=page_list, many=True)  # 多个many=True # instance：把对象序列化
        response = obj.get_paginated_response(ser.data)
        return response


from datetime import *
import requests

bt = [2.5, 3, 3.5, 4, 2, 2.8, 2.9, 3.1, 3.2, 3.4, 3.6]
check_in = date.today()
check_out = (date.today() + timedelta(days=1)).strftime("%Y-%m-%d")


# 接收白名单成员
def white_price(request):
    shid = request.GET.get('shid')
    srtid = request.GET.get('srtid')
    breakfast = request.GET.get('breakfast')
    nowtime = datetime.now()
    if not shid:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店shid'}))
    if not srtid:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店房型srtid'}))
    if not breakfast:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入早餐参数breakfast'}))
    try:
        html = requests.get(
            f'http://127.0.0.1:8000/feizhu/hotel_peer_price?page_num=0&room_code={srtid}&check_in={check_in}&check_out={check_out}&shid={shid}')
        json_data = json.loads(html.text)
        a = json_data['shid']
        b = json_data['room_code']
        c = json_data['seller']
        for d in range(len(c)):
            e = c[d]['seller_name']
            f = c[d]['describe']
            g = c[d]['item_id']
            rateid = c[d]['rate_id']
            h = c[d]['price']
            i = c[d]['breakfirst']
            if i == '无早':
                i = 0
            if i == '单早':
                i = 1
            if i == '双早':
                i = 2
            if i == '三早':
                i = 3
            print(e)
            itemobj = HotelItemPrice(shid=a, srtid=b, item_id=str(g), rate_id=str(rateid), sellernick=e, rtname=f,
                                     zhengce=str(i),
                                     price=str(h), create_time=nowtime, update_time=nowtime)
            itemobj.save()
    except:
        print('item自动录入失败')
    try:
        obj = HotelWhitePrice(shid=shid, srtid=srtid, zhengce=breakfast, create_time=nowtime, update_time=nowtime)
        obj.save()
        status = {'code': '200', 'msg': '录入成功'}
    except:
        status = {'code': '400', 'msg': '录入失败'}

    return HttpResponse(json.dumps(status))


# 删除白名单
def white_delete(request):
    shid = request.GET.get('shid')
    srtid = request.GET.get('srtid')
    breakfast = request.GET.get('breakfast')
    if not shid:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店shid'}))
    if not srtid:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店房型srtid'}))
    if not breakfast:
        return HttpResponse(json.dumps({'code': '400', 'msg': '请传入早餐参数breakfast'}))
    try:
        HotelWhitePrice.objects.filter(shid=shid, srtid=srtid, zhengce=breakfast).delete()
        status = {'code': '200', 'msg': '删除成功'}
    except:
        status = {'code': '400', 'msg': '删除失败'}
    return HttpResponse(json.dumps(status))


# 白名单分页输出
@api_view(['GET'])
def get_white(request, format=None):
    if request.method == 'GET':
        hotel_white_price = HotelWhitePrice.objects.all()
        obj = StandardMaxResultSetPagination()
        page_list = obj.paginate_queryset(hotel_white_price, request)
        ser = HotelWhitePriceSerializer(instance=page_list, many=True)  # 多个many=True # instance：把对象序列化
        response = obj.get_paginated_response(ser.data)
        return response


# 白名单条件查询
@api_view(['GET', 'POST'])
def get_white_code(request, format=None):
    if request.method == 'GET':
        shid = request.GET['shid']
        srtid = request.GET['srtid']
        breakfast = request.GET['breakfast']
        if not shid:
            return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店shid'}))
        if not srtid:
            return HttpResponse(json.dumps({'code': '400', 'msg': '请传入酒店房型srtid'}))
        if not breakfast:
            return HttpResponse(json.dumps({'code': '400', 'msg': '请传入早餐参数breakfast'}))
            # get是用来获取一个对象的，如果需要获取满足条件的一些数据，就要用到filter
        hotel_white_price = HotelWhitePrice.objects.filter(shid=shid, srtid=srtid, zhengce=breakfast)
        obj = StandardResultSetPagination()
        page_list = obj.paginate_queryset(hotel_white_price, request)
        ser = HotelWhitePriceSerializer(instance=page_list, many=True)
        response = obj.get_paginated_response(ser.data)
        return response


# 展示查询
@api_view(['GET', 'POST'])
def get_xx(request, format=None):
    hotel_item_xx = HotelItemXx.objects.filter(sellernick='成都成华阳鑫兴酒店专营店')
    obj = StandardMaxResultSetPagination()
    page_list = obj.paginate_queryset(hotel_item_xx, request)
    ser = HotelItemXxSerializer(instance=page_list, many=True)
    response = obj.get_paginated_response(ser.data)
    return response


@api_view(['GET', 'POST'])
def get_statu(request, format=None):
    if request.method == 'GET':
        statu = request.GET['statu']
        if statu is not None:
            nowtime = datetime.now()
            obj = HotelStatu(name='成都成华阳鑫兴酒店专营店', shirt_size=statu, create_time=nowtime)
            obj.save()
            return Response(str('成都成华阳鑫兴酒店专营店') + str(nowtime))
        else:
            return Response(str('请传statu'))


from django.db.models import Q


# 超能海豹非NULL名单
@api_view(['GET', 'POST'])
def get_xcid(request, format=None):
    if request.method == 'GET':
        hotel_xc_id = HotelXcId.objects.filter(hotel_id__isnull=False)
        serializer = HotelXcIdSerializer(hotel_xc_id, many=True)
        return Response(serializer.data)
